package com.foosun.core.service;

import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.foosun.core.base.BaseDao;
import com.foosun.core.base.BaseService;
import com.foosun.core.base.PageData;
import com.foosun.core.dao.ResourceDao;
import com.foosun.core.dao.RoleDao;
import com.foosun.core.entity.Role;
import com.foosun.core.entity.User;
import com.foosun.core.util.EncryptUtils;

@Service
@Transactional
public class UserService extends BaseService<User> {

    @Override
    @Resource(name = "userDao")
    public void setBaseDao(BaseDao<User> baseDao) {
        this.baseDao = baseDao;
    }


    @Resource
    private RoleDao roleDao;

    @Resource
    private ResourceDao resourceDao;
    

    /**
     * 用户登录，并获取用户信息
     *
     * @param userName
     * @param password
     * @return
     * @throws Exception
     */
    public User login(String userName, String password) throws Exception {
        User user = null;
        try {
            List<User> lst = findByProperty(new String[]{"user_name",
                    "password"}, new Object[]{userName, EncryptUtils.md5(password)});
            if (!lst.isEmpty()) {
                user = lst.get(0);
                Role role = roleDao.findById(user.getRole());
                user.setRoleData(role);
                LinkedHashMap<String, Object> resources = resourceDao.getResourceMap(role.getScope());
                user.setResources(resources);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return user;
    }

    public String saveImport(String path, int role) {
        return null;
    }


    @Override
    public PageData<User> findList(PageData<User> pageData) throws Exception {
        pageData = super.findList(pageData);
        List<User> users = pageData.getResult();
        for (User user : users) {
            user.setRoleData(roleDao.findById(user.getRole()));
        }
        return pageData;
    }

	@Override
	@Transactional
	public void delete(Integer id) throws Exception {
		super.delete(id);
		//删除和成员的关系
	}


    
    
}
